import hexMd5 from './md5';

function BoqiiAuth() {
   // H5 加密专用, 定期更换
   this.webToken = '214e1ba0-ce80-42d5-bda8-8e97c8dd7a2c';
   // 微信小程序 加密专用, 定期更换
   this.weappToken = '5a460249-e176-6f15-220f-7aab214e1ba0';
}

BoqiiAuth.prototype.signParams = function(params, from='web') {
  var token = this.webToken;
  if (from == 'weapp') {
    token = this.weappToken;
  }

  if ('Sign' in params) {
    delete params.Sign;
  }
  var newParamsWithOrder = this.sortByAscendingKeys(params);
  var stringToSign = this.joinValues(newParamsWithOrder) + token;
  return hexMd5(stringToSign);
};

BoqiiAuth.prototype.sortByAscendingKeys = function(obj) {
  var newObj = {};
  var keys = Object.keys(obj);
  keys = keys.sort(function(a, b) {
    if (a > b) return 1;
    if (a == b) return 0;
    return -1;
  });
  for (var i in keys) {
    newObj[keys[i]] = obj[keys[i]];
  }
  return newObj;
};

BoqiiAuth.prototype.joinValues = function(obj) {
  var self = this;
  if( Array.isArray(obj) ){
      return obj.map(function(v) {
        return self.joinValues(v);
      }).join(',');
  }else if( typeof obj === 'object' && typeof obj !== null ){
    obj = self.sortByAscendingKeys(obj);
    var objArr = [];
    for( var item in obj ){
      objArr.push(self.joinValues(obj[item]));
    }
    return objArr.join('');
  }else {
    // 其他直接转换成字符串返回
    return String(obj).valueOf();
  }
};

export default BoqiiAuth;
